package com.njit.postbar.adapter;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.njit.postbar.DynamicDesc;
import com.njit.postbar.Post;
import com.njit.postbar.R;
import com.njit.postbar.model.Dynamic;
import com.njit.postbar.model.Hide;
import com.njit.postbar.model.Like;
import com.njit.postbar.model.RoundImageView;
import com.njit.postbar.model.Star;
import com.njit.postbar.model.User;
import com.njit.postbar.utils.DateFormat;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 *@author yuruiqiao
 *@date 2020/6/6
 *@description 动态列表页,对每一个子项操作,监听器等
 */
public class DynamicListAdapter extends BaseAdapter {

    private List<Map<String, Object>> data;
    private LayoutInflater layoutInflater;
    private Context mContext;
    private User user,poster;
    private Dynamic dynamic;
    private boolean isStared,isLiked;
    public DynamicListAdapter(Context context, List<Map<String, Object>> data){
        this.data = data;
        this.layoutInflater = LayoutInflater.from(context);
        mContext = context;
    }
    /**
     * 组件集合，对应list.xml中的控件
     * @author Administrator
     */
    static class Component{
        RoundImageView headImage;
        TextView title;
        TextView userName;
        TextView time;
        RoundImageView image;
        TextView circle;
        TextView likeNum;
        TextView commentNum;
        Button more,update,delete,hide,star,bookmark,like;
        LinearLayout menu;
    }

    @Override
    public int getCount() {
        return data.size();
    }
    /**
     * 获得某一位置的数据
     */
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }
    /**
     * 获得唯一标识
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint({"InflateParams", "SetTextI18n"})
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //当前操作的用户
        user = (User)data.get(position).get("currentUser");
        final Component component;
        if(convertView == null){
            component = new Component();
            //获得组件,实例化组件
            convertView = layoutInflater.inflate(R.layout.item_dynamic, null);
            component.headImage = convertView.findViewById(R.id.item_activity_head_image);
            component.image = convertView.findViewById(R.id.item_activity_poster_image);
            component.title = convertView.findViewById(R.id.item_activity_poster_title);
            component.userName = convertView.findViewById(R.id.item_activity_poster_name);
            component.time = convertView.findViewById(R.id.item_activity_poster_time);
            component.circle = convertView.findViewById(R.id.item_activity_poster_circle);
            component.likeNum = convertView.findViewById(R.id.item_activity_like_num);
            component.commentNum = convertView.findViewById(R.id.item_activity_poster_comment_num);
            component.more = convertView.findViewById(R.id.more);
            component.update = convertView.findViewById(R.id.update);
            component.delete = convertView.findViewById(R.id.delete);
            component.menu = convertView.findViewById(R.id.menu);
            component.hide = convertView.findViewById(R.id.hide);
            component.star = convertView.findViewById(R.id.star);
            component.bookmark = convertView.findViewById(R.id.bookmark);
            component.like = convertView.findViewById(R.id.like_btn);
//            component.share = convertView.findViewById(R.id.share);
            convertView.setTag(component);
        }else{
            component=(Component)convertView.getTag();
        }
        //当前动态
        dynamic = (Dynamic)data.get(position).get("dynamic");
        assert dynamic != null;
        //动态所属用户
        poster = LitePal.find(User.class,dynamic.getUserId());
        //是否收藏
        isStared = (boolean) data.get(position).get("isStared");
        if(isStared){
            component.bookmark.setVisibility(View.VISIBLE);
            component.star.setText("取消收藏");
        }else{
            component.bookmark.setVisibility(View.INVISIBLE);
            component.star.setText("收藏");
        }
        //是否点赞
        isLiked = (boolean) data.get(position).get("isLiked");
        if(isLiked){
            component.like.setBackground(mContext.getDrawable(R.drawable.ic_thumb_up_on));
            component.likeNum.setTextColor(mContext.getColor(R.color.main));
        }else{
            component.like.setBackground(mContext.getDrawable(R.drawable.ic_thumb_up));
            component.likeNum.setTextColor(mContext.getColor(R.color.plain));
        }
        //预览图
        if("".equals(dynamic.getPreviewImageUrl())){
            component.image.setVisibility(View.GONE);
        }else{
            Glide.with(mContext).load(dynamic.getPreviewImageUrl()).into(component.image);
        }
        Glide.with(mContext).load(poster.getHeadImage()).into(component.headImage);
        component.title.setText(dynamic.getTitle());
        component.userName.setText(poster.getUserName());
        //时间格式
        if(dynamic.getUpdateTime()!=null){
            component.time.setText("更新于"+DateFormat.timeDetails(dynamic.getUpdateTime()));
            component.time.setTextColor(mContext.getResources().getColor(R.color.colorAccent,mContext.getTheme()));
        }
        else{
            component.time.setText("发布于"+DateFormat.timeDetails(dynamic.getCreateTime()));
        }
        component.circle.setText(dynamic.getCircle());
        component.likeNum.setText(dynamic.getLikeNumber()+"");
        component.commentNum.setText(dynamic.getCommentNumber()+"");
        //如果是作者本人,有修改和删除的权限,否则有收藏和隐藏的权限
        if (user == null||user.getId() != poster.getId()) {
            component.hide.setVisibility(View.VISIBLE);
            component.star.setVisibility(View.VISIBLE);
            component.update.setVisibility(View.GONE);
            component.delete.setVisibility(View.GONE);
        }else{
            component.update.setVisibility(View.VISIBLE);
            component.delete.setVisibility(View.VISIBLE);
            component.hide.setVisibility(View.GONE);
            component.star.setVisibility(View.GONE);
        }
        //点击整个子项进入详情页
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始传值
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                poster = LitePal.find(User.class,dynamic.getUserId());
                Intent intent = new Intent(mContext, DynamicDesc.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("dynamic",dynamic);
                bundle.putSerializable("poster",poster);
                intent.putExtras(bundle);
                //利用上下文开启跳转
                mContext.startActivity(intent);
                component.menu.setVisibility(View.GONE);

            }
        });
        //点击子项右上角的三个小圆点
        component.more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(component.menu.getVisibility() == View.GONE){
                    component.menu.setVisibility(View.VISIBLE);
                }else{
                    component.menu.setVisibility(View.GONE);
                }
            }
        });
        //点击修改
        component.update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, Post.class);
                Bundle bundle = new Bundle();
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                bundle.putSerializable("user",user);
                bundle.putSerializable("dynamic",dynamic);
                intent.putExtras(bundle);
                //利用上下文开启跳转
                mContext.startActivity(intent);
                component.menu.setVisibility(View.GONE);
            }
        });
        //点击删除
        component.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                poster = LitePal.find(User.class,dynamic.getUserId());
                //如果用户身份核实再删除,否则无法删除
                if(user.getId() == poster.getId()){
                    confirmDialog("确认删除动态？",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            LitePal.delete(Dynamic.class,dynamic.getId());
                        }
                    });
                }else {
                    showDialog("非法操作","您没有权限😭");
                }
                component.menu.setVisibility(View.GONE);
            }
        });
        //点击隐藏
        component.hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                if(user==null){
                    showDialog("提示","请先登录😅");
                }else if(!isStared && !isLiked) {
                    confirmDialog("确认要隐藏我吗😭？",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Hide hideDynamic = new Hide();
                            hideDynamic.setTargetType(Hide.DYNAMIC);
                            hideDynamic.setTargetId(dynamic.getId());
                            hideDynamic.setUserId(user.getId());
                            hideDynamic.setState(true);
                            hideDynamic.save();
                            Toast.makeText(mContext, "隐藏成功", Toast.LENGTH_LONG).show();
                        }
                    });
                    component.menu.setVisibility(View.GONE);
                    //收藏状态无法隐藏
                }else{
                    showDialog("提示","请先取消收藏或取消点赞");
                }
            }
        });
        //点击收藏
        component.star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                poster = LitePal.find(User.class,dynamic.getUserId());
                List<Star> stars = new ArrayList<>();
                //用户未登录的情况
                if(user!=null){
                    stars = LitePal.where("userid=? and targettype=? and targetid=?",
                            user.getId()+"",Star.DYNAMIC,dynamic.getId()+"").find(Star.class);
                }
                Star star = null;
                if(stars.size() > 0)
                    star = stars.get(0);
                if(user!=null){
                    if(star == null){
                        star = new Star();
                        star.setTargetType(Star.DYNAMIC);
                        star.setTargetId(dynamic.getId());
                        star.setUserId(user.getId());
                        star.setIsStared(true);
                        star.save();
                        showDialog("来自用户","感谢收藏 😚😚😚");
                    }
                    //如果已经被收藏,则取消收藏
                    else if(star.getIsStared()){
                        star.setIsStared(false);
                        star.save();
                        showDialog("提示","已取消收藏😞");
                        component.star.setText("收藏");
                        component.bookmark.setVisibility(View.INVISIBLE);
                    }else{
                        star.setIsStared(true);
                        star.save();
                        showDialog("来自用户","感谢收藏 😚😚😚");
                        component.star.setText("取消收藏");
                        component.bookmark.setVisibility(View.VISIBLE);
                    }
                    component.menu.setVisibility(View.GONE);
                }else {
                    showDialog("提示","请先登录😅");
                }
            }
        });
        //点赞动态
        component.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dynamic = (Dynamic)data.get(position).get("dynamic");
                assert dynamic != null;
                poster = LitePal.find(User.class,dynamic.getUserId());
                List<Like> likes = new ArrayList<>();
                //用户未登录的情况
                if(user!=null){
                    likes = LitePal.where("userid=? and targettype=? and targetid=?",
                            user.getId()+"",Like.DYNAMIC,dynamic.getId()+"").find(Like.class);
                }
                Like like = null;
                if(likes.size()>0)
                    like = likes.get(0);
                if(user!=null){
                    if(like == null){
                        like = new Like();
                        like.setTargetType(Star.DYNAMIC);
                        like.setTargetId(dynamic.getId());
                        like.setUserId(user.getId());
                        like.setIsLiked(true);
                        like.save();
                        int old = Integer.parseInt(component.likeNum.getText().toString());
                        component.likeNum.setText(1+old+"");
                        component.like.setBackground(mContext.getDrawable(R.drawable.ic_thumb_up_on));
                        component.likeNum.setTextColor(mContext.getColor(R.color.main));
                    }
                    //如果已经点赞,则取消点赞
                    else if(like.getIsLiked()){
                        like.setIsLiked(false);
                        like.save();
                        int old = Integer.parseInt(component.likeNum.getText().toString());
                        component.likeNum.setText(old-1+"");
                        component.like.setBackground(mContext.getDrawable(R.drawable.ic_thumb_up));
                        component.likeNum.setTextColor(mContext.getColor(R.color.plain));
                    }else{
                        like.setIsLiked(true);
                        like.save();
                        int old = Integer.parseInt(component.likeNum.getText().toString());
                        component.likeNum.setText(1+old+"");
                        component.like.setBackground(mContext.getDrawable(R.drawable.ic_thumb_up_on));
                        component.likeNum.setTextColor(mContext.getColor(R.color.main));
                    }
                }else {
                    showDialog("提示","请先登录😅");
                }
            }
        });
        //点击分享
//        component.share.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
        return convertView;
    }

    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 选择确认框
     */
    private void confirmDialog(String message, DialogInterface.OnClickListener listener){
        AlertDialog.Builder builder  = new AlertDialog.Builder(mContext);
        builder.setTitle("请确认") ;
        builder.setMessage(message) ;
        builder.setPositiveButton("是😞", listener);
        builder.setNegativeButton("否",null);
        builder.show();
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 提示框
     */
    private void showDialog(String title,String message){
        AlertDialog.Builder builder  = new AlertDialog.Builder(mContext);
        builder.setTitle(title) ;
        builder.setMessage(message) ;
        builder.setPositiveButton("是" ,  null );
        builder.show();
    }
}
